package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.security.auth.login.LoginException;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;


@Service
public class UserInfoServiceImpl implements IUserInfoService {


    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;


    @Override
    public void save(UserInfo userInfo) {
        userInfo.setId(null);
        userInfoRepository.save(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoRepository.save(userInfo);
    }

    @Override
    public void delete(String id) {
        userInfoRepository.deleteById(id);
    }

    @Override
    public UserInfo get(String id) {
        return userInfoRepository.findById(id).orElse(null);
    }

    @Override
    public List<UserInfo> list() {
        return userInfoRepository.findAll();
    }

    @Override
    public boolean findByPhone(String phone) {
        //通过手机号查询是否有用户对象
        UserInfo userInfo = userInfoRepository.findByPhone(phone);
        //如果用户对象
        return userInfo != null;
    }

    @Override
    public void sendVerifyCode(String phone, String smsurl, String appkey) {
        //使用uuid生成随机验证码
        String code = UUID.randomUUID().toString().replace("-", "").substring(0, 4);
        StringBuffer sb = new StringBuffer(80);

        sb.append("您的验证码为:").append(code).append(",").append("有效时间为").
                append(Consts.VERIFY_CODE_VAI_TIME).append("分钟");
        System.out.println(sb.toString());

       /* String url = "https://way.jd.com/chuangxin/dxjk?" +
                "mobile=" + phone + "&" +
                "content=【java课程】你的验证码是：" + sb.toString() + "，3分钟内有效！&" +
                "appkey=eb255371cc87e94dcd69ba28496e6a8a";*/
        //spring提供http发送请求（真实发送短信）
      /*  RestTemplate restTemplate = new RestTemplate();

        //第一个参数为路径，第二个参数为返回类型(由于返回是kv对，可以为String，也可以map),第三个参数
        String ret = restTemplate.getForObject(smsurl, String.class,phone,"【java课程】"+sb.toString(),appkey);
        if (!ret.contains("Success")) {
            throw new LogicException("验证码发送失败");
        }*/
        //将参数phone作为key，code作为value存入redis缓存中
        userInfoRedisService.sendVerifyCode(phone, code);


    }

    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        //需要判断传入的参数是否为null，通过定义断言工具类内进行判断
        AssertUtil.hasLength(phone, "手机号码不能为空");
        AssertUtil.hasLength(nickname, "昵称不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "确认密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");
        //需要判断传入的两次输入的密码是否一致
        AssertUtil.isEquals(password, rpassword, "两次输入密码不一致");
        //判断手机号是否符合格式
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";
        if (!Pattern.matches(regex, phone)) {
            throw new LogicException("手机格式不正确");
        }


        //判断手机号是否唯一
        if (this.findByPhone(phone)) {
            throw new LogicException("该手机号已经被注册");
        }

        //判断验证码是否正确
        String code = userInfoRedisService.getVerifyCode(phone);
        if (code == null || !code.equalsIgnoreCase(verifyCode)) {
            throw new LogicException("验证码已失效或者有误");
        }


        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(phone);
        userInfo.setNickname(nickname);
        userInfo.setPassword(password);
        userInfo.setLevel(1);
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setCity("");
        userInfo.setInfo("");
        //关键字段自己控制
        userInfo.setState(UserInfo.GENDER_SECRET);
      /*  模拟保存过程中后台出错
       throw new RuntimeException("ndsifonsofnfsonf");*/
        this.save(userInfo);
    }

    @Override
    public UserInfo login(String username, String password) {
        UserInfo userInfo = userInfoRepository.findByPhone(username);
        if(userInfo == null || !password.equals(userInfo.getPassword()) ){
            throw new LogicException("你的账号密码有误");
        }
        return userInfo;
    }

    @Override
    public List<UserInfo> queryByDestName(String destname) {

        return userInfoRepository.findByCity(destname);
    }
}
